package com.yunke.common.exception;

import com.yunke.common.result.YunkeResult;
import com.yunke.common.result.YunkeResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import java.sql.SQLException;
import java.util.Set;

/**
 * 云科搭子系统全局异常处理器
 * 
 * @author yunke
 * @since 1.0.0
 */
@Slf4j
@RestControllerAdvice
public class YunkeGlobalExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(YunkeException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleYunkeException(YunkeException e, HttpServletRequest request) {
        log.error("业务异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return YunkeResult.error(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常 - @RequestBody参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("; ");
        }
        String message = errorMsg.toString();
        log.error("参数校验异常: {}, 请求路径: {}", message, request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理参数校验异常 - @ModelAttribute参数校验
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleBindException(BindException e, HttpServletRequest request) {
        StringBuilder errorMsg = new StringBuilder();
        for (FieldError fieldError : e.getBindingResult().getFieldErrors()) {
            errorMsg.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("; ");
        }
        String message = errorMsg.toString();
        log.error("参数绑定异常: {}, 请求路径: {}", message, request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理参数校验异常 - @RequestParam和@PathVariable参数校验
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        StringBuilder errorMsg = new StringBuilder();
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        for (ConstraintViolation<?> violation : violations) {
            errorMsg.append(violation.getPropertyPath()).append(": ").append(violation.getMessage()).append("; ");
        }
        String message = errorMsg.toString();
        log.error("约束校验异常: {}, 请求路径: {}", message, request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理参数类型转换异常
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String message = String.format("参数类型错误: %s 应该是 %s 类型", e.getName(), e.getRequiredType().getSimpleName());
        log.error("参数类型转换异常: {}, 请求路径: {}", message, request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.PARAM_ERROR.getCode(), message);
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常, 请求路径: {}", request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.INTERNAL_SERVER_ERROR.getCode(), "系统内部错误，请联系管理员");
    }

    /**
     * 处理数据库异常
     */
    @ExceptionHandler(SQLException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleSQLException(SQLException e, HttpServletRequest request) {
        log.error("数据库异常, 请求路径: {}", request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.DATABASE_ERROR.getCode(), "数据库操作异常");
    }

    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        log.error("非法参数异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.PARAM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        log.error("运行时异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.INTERNAL_SERVER_ERROR.getCode(), "系统内部错误");
    }

    /**
     * 处理其他未知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public YunkeResult<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("未知异常: {}, 请求路径: {}", e.getMessage(), request.getRequestURI(), e);
        return YunkeResult.error(YunkeResultCode.INTERNAL_SERVER_ERROR.getCode(), "系统异常，请稍后重试");
    }
} 